package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.QuanZiService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.VideoMQService;
import com.tanhua.server.service.VideoService;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.UserTokenHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoServiceImpl implements VideoService {


    @Reference(version = "1.0.0")
    private VideoApi videoApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private QuanZiService quanZiService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private VideoMQService videoMQService;

    @Override
    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        Video video=new Video();
        User user = UserThreadLocal.get();
        video.setUserId(user.getId());
        video.setSeeType(1);
        //上传图片
        try {
            PicUploadResult upload = this.picUploadService.upload(picFile);
            video.setPicUrl(upload.getName());
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(),".",true), null);
            String videoUrl=fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
            video.setVideoUrl(videoUrl);
            String videoId = this.videoApi.saveVideo(video);
            if (StrUtil.isNotEmpty(videoId)) {
                this.videoMQService.videoMsg(videoId);
                return true;
            }

            return false;
        } catch (IOException e) {
            log.error("视频上传出错!userId="+user.getId()+",文件为fileName="+videoFile.getOriginalFilename(),e);
        }
        
        return false;
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : records) {
            VideoVo videoVo=new VideoVo();
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setUserId(video.getUserId());
            videoVo.setId(video.getId().toHexString());
            videoVo.setCover(video.getPicUrl());//封面

            videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(videoVo.getId())));//TODO 评论数
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//TODO 点赞数
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(),videoVo.getId())?1:0);//TODO 是否点赞
            videoVo.setHasFocus(this.videoApi.isFollowUser(user.getId(),videoVo.getUserId())?1:0);//是否关注
            videoVo.setSignature("我就是我,颜色不一样的花火");//TODO 签名
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getUserId().longValue()==video.getUserId().longValue()) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }
            videoVoList.add(videoVo);
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    @Override
    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        boolean data=this.quanZiApi.disLikeComment(user.getId(),videoId);
        if (data){
            //发送消息
            this.videoMQService.disLikeVideoMsg(videoId);

            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 点赞
     * @param publishId
     * @return
     */
    @Override
    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        boolean data=this.quanZiApi.likeComment(user.getId(),videoId);
        if (data){
            //发送消息
            this.videoMQService.disLikeVideoMsg(videoId);

            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    @Override
    public Boolean saveComment(String videoId, String content) {
        Boolean aBoolean = this.quanZiService.saveComments(videoId, content);
        if (aBoolean){
            //发送消息
            this.videoMQService.commentVideoMsg(videoId);
        }
        return aBoolean;
    }

    @Override
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {

        return this.quanZiService.queryCommentList(videoId, page, pageSize);
    }

    @Override
    public Boolean followUser(Long followUserId) {
        User user = UserThreadLocal.get();
        return this.videoApi.followUser(user.getId(),followUserId);
    }

    @Override
    public Boolean disFollowUser(Long followUserId) {
        User user = UserThreadLocal.get();
        return this.videoApi.disFollowUser(user.getId(),followUserId);
    }
}
